https://leetcode.com/problems/search-insert-position/
已知一個排序好的陣列與目標值,如有找到目標值返回其索引值,如果沒有則返回按順序插入的索引。
利用二分法原理判斷符合為目標值,是的話直接返回其索引值,不是的話利用二分法逼近其索引位置,以此循環
int searchInsert(int* nums, int numsSize, int target) {
int left = 0, right = numsSize-1;
while(left <= right)
{
int mid = left + (right - left)/2 ;
if(nums[mid] == target)
{
return mid;
}
else if(nums[mid] > target)
{
right = mid -1;
}
else
{
left = mid +1;
}
}
return left;
}
var searchInsert = function(nums, target) {
var left = 0, right = nums.length-1;
while(left <= right)
{
var mid = parseInt((left + right)/2) ;
if(nums[mid] == target)
{
return mid;
}
else if(nums[mid] > target)
{
right = mid -1;
}
else
{
left = mid +1;
}
}
return left;
};
https://github.com/SIAOYUCHEN/leetcode
https://ithelp.ithome.com.tw/users/20100009/ironman/2500
https://ithelp.ithome.com.tw/users/20113393/ironman/2169
https://ithelp.ithome.com.tw/users/20107480/ironman/2435
https://ithelp.ithome.com.tw/users/20107195/ironman/2382
https://ithelp.ithome.com.tw/users/20119871/ironman/2210
https://ithelp.ithome.com.tw/users/20106426/ironman/2136
The problem is not the problem, the problem is your attitude about your problem.
問題本身不是問題,面對問題時的態度才是問題